using System;
using System.Linq;
using System.Reflection;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.Extensions;
using IdentityServer4.Validation;
using Idp_Login._idp_config_;
using Idp_Login.Configs;
using Idp_Login.Configs.Id4;
using Idp_Login.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StackExchange.Redis;

namespace Idp_Login
{
    public class Startup
    {
        private Id4 id4Setting = new Id4();
        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            Console.Title = Assembly.GetExecutingAssembly().GetName().Name;
            Environment = env;

            Configuration = configuration;
            configuration.GetSection("id4").Bind(id4Setting);
        }
        public IWebHostEnvironment Environment { get; }

        public IConfiguration Configuration { get; }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddTransient<ICustomTokenRequestValidator, DefaultClientClaimsAdder>();

            //https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0
            services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });
             

            #region DataProtection + 使用Redis保存Session
            //DataProtection 要在services.ConfigId4() 之前

            var redisConnStr = id4Setting.DataProtection.SaveToRedis.RedisConnectionString;//获取Redis 连接字符串
            var redis = StackExchange.Redis.ConnectionMultiplexer.Connect(redisConnStr); //建立Redis 连接 


            //添加数据保护服务，设置统一应用程序名称，并指定使用Reids存储私钥
            var dataProtect = services.AddDataProtection();
            //dataProtect.PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");

            var redisDbIndex = id4Setting.DataProtection.SaveToRedis.Db;
            var databaseFactory = (Func<IDatabase>)(() => redis.GetDatabase(redisDbIndex));

            var key = id4Setting.DataProtection.SaveToRedis.PersistKeys ?? Assembly.GetExecutingAssembly().GetName().Name;
            //<PackageReference Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" Version="5.0.4" />
            dataProtect.PersistKeysToStackExchangeRedis(databaseFactory, key);

            var applicationName = id4Setting.DataProtection.ApplicationName ?? Assembly.GetExecutingAssembly().GetName().Name;
            dataProtect.SetApplicationName(applicationName);


            //添加Redis缓存用于分布式Session
            //<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="5.0.1" />
            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = id4Setting.DistributedSessionRedis.RedisConnectionString;
                options.InstanceName = Assembly.GetExecutingAssembly().GetName().Name;
            });

            services.AddSession(options =>
            {
                options.Cookie.Name = Assembly.GetExecutingAssembly().GetName().Name;
                options.IdleTimeout = TimeSpan.FromMinutes(10); //设置session的过期时间
                options.Cookie.HttpOnly = true; //设置在浏览器不能通过js获得该cookie的值
                options.Cookie.IsEssential = true;
            });

            services.AddSession();

            #endregion

            services.ConfigId4(Environment, id4Setting);

            var connectionString = Configuration.GetConnectionString("DefaultConnection");
            services.AddDbContextPool<IdpContext>(options => options.UseSqlServer(connectionString));//注入DbContext

            services.AddControllersWithViews();
            services.AddTransient<IAdminService, AdminService>();//service注入
        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (!string.IsNullOrEmpty(id4Setting.Authority))
            {
                //options.PublicOrigin = id4Setting.Authority;//id4 v4 没有了
                //v4具体的处理方法可以参考  https://www.cnblogs.com/stulzq/p/13818199.html
                app.Use(async (ctx, next) =>
                {
                    //ctx.SetIdentityServerOrigin(id4Setting.Authority);
                    Console.WriteLine("id4地址/nginx 反向代理为:" + id4Setting.Authority);
                    ctx.SetIdentityServerOrigin(id4Setting.Authority);
                    await next();
                });
            }

            //Id4InitializeDatabase.InitializeDatabase(app); //初始化id4配置到数据库

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            // 1) ConfigureHttpsForwardingBehindProxy 和 2) app.UseIdentityServer();的顺序 (网上到的, 不知道真假),
            // 1) 2)   Then you become https.      2) 1)   Then you will get http 
            app.ConfigureHttpsForwardingBehindProxy();
            //添加ids4服务中间件（注意要放在UseMvc之前就可以）
            app.UseIdentityServer();

            //使用Cookie决策
            //Add this before any other middleware that might write cookies
            // 在任何其他可能编写cookie的中间件之前添加此项
            app.UseCookiePolicy();//使上面的services.Configure<CookiePolicyOptions>生效

            // This will write cookies, so make sure it's after the cookie policy
            app.UseAuthentication();

            app.UseHttpsRedirection();

            //app.UseStaticFiles();//改成这个就可以了
            app.UseStaticFilesWrap(env);  //cmd下, 直接启动, 静态文件找不到, 我给包装了一下,去找上级目录

            //app.UseSession();
            app.UseRouting();
            app.UseCors("AllowCors");

            app.UseAuthorization(); //使用默认UI，必须添加

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
